<template>
    <div class="app-container calendar-list-container">
        <div class="filter-container">
            <el-input
                    @keyup.enter.native="getData"
                    clearable
                    v-model="listQuery.attributeMaintenanceCustomerName"
                    style="width: 150px;margin-right:15px;margin-top:7px"
                    class="filter-item"
                    placeholder="请选择客户名称"
            ></el-input>
            <el-input
                    @keyup.enter.native="getData"
                    clearable
                    v-model="listQuery.attributeMaintenanceProductType"
                    style="width: 180px;margin-right:15px;margin-top:7px"
                    class="filter-item"
                    placeholder="请选择产品类型"
            ></el-input>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
            <el-button v-if="userInfo.roleId == 29 || userInfo.roleId == 14" class="filter-item" type="success" icon="el-icon-plus" @click="addShow('新增')">新增</el-button>
        </div>

        <!-- 表单 -->
        <el-table :data="dealList" v-loading="listLoading" element-loading-text="拼命加载中"  stripe border fit highlight-current-row style="width: 100%">
          <el-table-column label="序号" type="index" align="center" width="80px">
           <template slot-scope="scope">
            {{ (listQuery.page - 1) * listQuery.limit + scope.$index + 1 }}
           </template>
          </el-table-column>
            <el-table-column  label="客户名称" prop="attributeMaintenanceCustomerName" align="center"/>
            <el-table-column  label="产品类型" prop="attributeMaintenanceProductType" align="center"/>
            <el-table-column  label="商务人员" prop="attributeMaintenanceCommercialPersonnelUserName" align="center"/>
            <el-table-column  label="计划人员" prop="attributeMaintenanceProjectPersonnelUserName" align="center"/>
            <el-table-column  label="数控占比" prop="attributeMaintenanceNumericalControlProportion" align="center"/>
            <el-table-column  label="焊接占比" prop="attributeMaintenanceWeldProportion" align="center"/>
            <el-table-column  label="喷涂占比" prop="attributeMaintenanceSprayProportion" align="center"/>
            <el-table-column  label="装配产能" prop="attributeMaintenanceAssembleProportion" align="center"/>
            <el-table-column  label="邮件接收人" prop="attributeMaintenanceMailUserName" align="center"/>
            <el-table-column  label="修改人员" prop="attributeMaintenanceUpdateUserName" align="center"/>
            <el-table-column  label="修改时间" prop="attributeMaintenanceUpdateTime" align="center"/>
            <!-- 对oneNET进行修改与删除 -->
            <el-table-column  label="操作" align="center" width="230">
            <template slot-scope="scope" >
                <el-button v-if="userInfo.roleId == 29 || userInfo.roleId == 14" size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                <el-button v-if="userInfo.roleId == 14" size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
            </template>
            </el-table-column>
        </el-table>

           <!-- pagination 分页 -->
        <div class="pagination-container">
            <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.page"
            :page-sizes="[5,10, 20, 30, 40,100,300,500]"
            :page-size="listQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            ></el-pagination>
        </div>
        
             <!-- <el-divider></el-divider> -->
        
        <el-button type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

        <!-- 修改工段信息弹出表单 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="700px" @close="closeReset">
            <el-form :model="modifyform" :rules="rules" ref="formName">
                <el-form-item prop="attributeMaintenanceCustomerName" label="客户名称" :label-width="formLabelWidth">
                    <el-input :disabled="title == '修改'" v-model="modifyform.attributeMaintenanceCustomerName" style="width:400px"/>
                </el-form-item>
                <el-form-item prop="attributeMaintenanceProductType" label="产品类型" :label-width="formLabelWidth">
                    <el-input :disabled="title == '修改'" v-model="modifyform.attributeMaintenanceProductType" style="width:400px" />
                </el-form-item>
                <div style="display: flex;">
                  <el-form-item prop="attributeMaintenanceCommercialPersonnelUserName" label="商务人员" :label-width="formLabelWidth">
                    <el-select filterable @focus="businessFocus" v-model="modifyform.attributeMaintenanceCommercialPersonnelUserName" placeholder="请选择" style="width:150px">
                        <el-option
                          v-for="(item,index) in personnelList"
                          :key="index"
                          :label="item.userName"
                          :value="item.userName">
                        </el-option>
                      </el-select>
                  </el-form-item>
                  <el-form-item prop="attributeMaintenanceProjectPersonnelUserName" label="计划人员" :label-width="formLabelWidth">
                    <el-select filterable  @focus="businessFocus" v-model="modifyform.attributeMaintenanceProjectPersonnelUserName" placeholder="请选择" style="width:150px">
                        <el-option
                          v-for="(item,index) in personnelList"
                          :key="index"
                          :label="item.userName"
                          :value="item.userName">
                        </el-option>
                      </el-select>
                  </el-form-item>
                </div>
                <div style="display: flex;">
                  <el-form-item prop="attributeMaintenanceNumericalControlProportion" label="数控占比" :label-width="formLabelWidth">
                    <el-select v-model="modifyform.attributeMaintenanceNumericalControlProportion" placeholder="请选择" style="width:100px">
                      <el-option
                        v-for="(item,index) in portionList"
                        :key="index"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="attributeMaintenanceWeldProportion" label="焊接占比" :label-width="formLabelWidth">
                    <el-select v-model="modifyform.attributeMaintenanceWeldProportion" placeholder="请选择" style="width:100px">
                      <el-option
                        v-for="(item,index) in portionList"
                        :key="index"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item prop="attributeMaintenanceSprayProportion" label="喷涂占比" :label-width="formLabelWidth">
                    <el-select v-model="modifyform.attributeMaintenanceSprayProportion" placeholder="请选择" style="width:100px">
                      <el-option
                        v-for="(item,index) in portionList"
                        :key="index"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div style="display: flex;">
                  <el-form-item prop="attributeMaintenanceAssembleProportion" label="装配日产能" :label-width="formLabelWidth">
                      <el-input v-model.number="modifyform.attributeMaintenanceAssembleProportion" style="width:100px" />
                  </el-form-item>
                  <el-form-item label="邮件接收人" :label-width="formLabelWidth">
                      <!-- <el-input v-model="modifyform.attributeMaintenanceMailUserName" style="width:400px" /> -->
                      <!-- <el-select @change="mailChang" filterable @focus="businessFocus" v-model="modifyform.attributeMaintenanceMailUserName" placeholder="请选择" style="width:150px">
                        <el-option
                          v-for="(item,index) in personnelList"
                          :key="index"
                          :label="item.userName"
                          :value="item.userName">
                        </el-option>
                      </el-select> -->
                      <div v-for="(items,index1) in MailUserName" :key="index1" style="margin-bottom: 5px;">
                        <el-select  @change="mailChang($event,index1)" filterable @focus="businessFocus" v-model="items.name" placeholder="请选择" style="width:150px">
                          <el-option
                          v-for="(item,index) in personnelList"
                          :key="index"
                          :label="item.userName"
                          :value="item.userName">
                        </el-option>
                      </el-select>
                      <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delMail(index1)"></el-button>
                      <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addMail"></el-button>
                    </div>
                  </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button @click="closeReset">取 消</el-button>
            <el-button type="primary" @click="modifyWorkSec">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { orderForecasting,baselineSave,baselineUpd,maintenanceDel } from '../../api/planManagement.js'
import { searchWorkers } from '../../api/chargingData.js'
export default {
  name:'attribute_Maintenance',
    data() {
        return {
          // 获取人员列表
          personnelList:'',
          portionList:['10%','20%','30%','40%','50%','60%','70%','80%','90%','100%'],
            listQuery: {
                page: 1,
                limit: 10,
                isDelete: 0
            },
            modifyform: {
              attributeMaintenanceCustomerName:'',
              attributeMaintenanceProductType:'',
              attributeMaintenanceCommercialPersonnelUserName:'',
              attributeMaintenanceProjectPersonnelUserName:'',
              attributeMaintenanceNumericalControlProportion:'',
              attributeMaintenanceWeldProportion:'',
              attributeMaintenanceSprayProportion:'',
              attributeMaintenanceAssembleProportion:'',
              attributeMaintenanceMailUserName:'',
            },
            rules: {
              attributeMaintenanceCustomerName: [
                  { required: true, message: '请输入客户名称', trigger: 'blur' }
                ],
              attributeMaintenanceProductType: [
                { required: true, message: '请选择产品类型', trigger: 'blur' }
              ],
              attributeMaintenanceCommercialPersonnelUserName: [
                { required: true, message: '请选择商务人员', trigger: 'blur' }
              ],
              attributeMaintenanceProjectPersonnelUserName: [
                { required: true, message: '请选择计划人员', trigger: 'blur' }
              ],
              attributeMaintenanceNumericalControlProportion: [
                { required: true, message: '请输入数控占比', trigger: 'blur' }
              ],
              attributeMaintenanceWeldProportion: [
                { required: true, message: '请输入焊接占比', trigger: 'blur' }
              ],
              attributeMaintenanceSprayProportion: [
                { required: true, message: '请输入喷涂占比', trigger: 'blur' }
              ],
              attributeMaintenanceAssembleProportion: [
                { required: true, message: '请输入装配日产能', trigger: 'blur' },
                { type: 'number', message: '产能必须为数字值', trigger: 'blur' },
              ]
            },
            attributeMaintenanceMail:[],
            MailUserName:[{name:''}],
            dealList: '',
            total: 0,
            listLoading: false,
            dialogFormVisible: false,
            formLabelWidth: '100px',
            userInfo: this.$store.state.user.userInfo,
            title: '新增'
        }
    },
    methods: {
      closeReset(){
        this.modifyform = {
          attributeMaintenanceCustomerName:'',
          attributeMaintenanceProductType:'',
          attributeMaintenanceCommercialPersonnelUserName:'',
          attributeMaintenanceProjectPersonnelUserName:'',
          attributeMaintenanceNumericalControlProportion:'',
          attributeMaintenanceWeldProportion:'',
          attributeMaintenanceSprayProportion:'',
          attributeMaintenanceAssembleProportion:'',
          attributeMaintenanceMailUserName:'',
        }
        this.$refs.formName.resetFields()
        this.attributeMaintenanceMail = []
        this.MailUserName = [{name:''}]
        this.dialogFormVisible = false
      },
      // 打开弹框
      addShow(title){
        console.log(this.attributeMaintenanceMail);
        console.log(this.MailUserName);
        this.title = title
        this.dialogFormVisible = true
      },
      // 添加邮箱
      addMail(){
        this.MailUserName.push({name:''})
        // this.attributeMaintenanceMail.push('')
        console.log(this.attributeMaintenanceMail);
      },
      // 删除邮箱
      delMail(index){
        if(this.MailUserName.length == 1){
          this.MailUserName = [{name:''}]
          this.attributeMaintenanceMail = []
        } else {
          this.MailUserName.splice(index, 1);
          this.attributeMaintenanceMail.splice(index, 1);
          console.log(this.attributeMaintenanceMail);
        }
      },
      // 邮箱发生改变
      mailChang(e,index1){
        this.personnelList.forEach(item => {
          if(e){
            if(e === item.userName){
              if(item.mail && item.mail !== 'null'){
                console.log(this.MailUserName);
                if(this.attributeMaintenanceMail[index1]){
                  this.attributeMaintenanceMail[index1] = item.mail
                } else {
                  this.attributeMaintenanceMail.splice(index1, 0, item.mail)
                }
                console.log(this.attributeMaintenanceMail);
                // this.modifyform.attributeMaintenanceMail = item.mail
              } else {
                  this.$message({
                    message: `${e}没有添加邮箱！`,
                    type: 'warning'
                  })
                  this.MailUserName[index1].name = ''
              }
            }
          }
        })
      },
      // 搜索按钮定义的函数
      async handleFilter() {
        this.listLoading = true
        let query = Object.assign({},this.listQuery)
        const res = await orderForecasting(query)
        this.dealList = res.data.list
        this.total = res.data.count
        this.listLoading = false
      },
      async businessFocus(){
        if(!this.personnelList.length) {
          const res = await searchWorkers({page:1,limit:9999,status: 1})
          this.personnelList = res.data.records
        }
      },
    // 删除用户按钮,使用elementui的messageBox弹框组件
    handleDelete(index,row) {
      this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let res = await maintenanceDel({id: row.id,isDelete: 1})
          // this.dealList.splice(index, 1)
          if(res.code == 1){
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.handleFilter()
        } else {
          this.$message({
            type: 'error',
            message: `${res.msg}`
          })
        }
        }).catch(() => {
          this.$message({
            type: 'info', 
            message: '已取消删除'
          })
        })
    },
    // 将弹框修改后的工段信息传入后台，并且消息提示是否修改成功
      async modifyWorkSec() {
        // console.log(this.MailUserName);
        // console.log(this.attributeMaintenanceMail);
        await this.$refs.formName.validate()
        let str1 = this.MailUserName.map(obj => obj.name).join(',');
        let str = this.attributeMaintenanceMail.join(',');
        let query = Object.assign({},this.modifyform)
        query.attributeMaintenanceMailUserName = str1
        query.attributeMaintenanceMail = str
        const data1 = await searchWorkers({page:1,limit:10,status: 1,username:query.attributeMaintenanceCommercialPersonnelUserName})
        const data2 = await searchWorkers({page:1,limit:10,status: 1,username:query.attributeMaintenanceProjectPersonnelUserName})
        console.log(data1);
        if(data1.data.records.length == 0) return this.$message.error('商务人员是停用状态');
        if(data2.data.records.length == 0) return this.$message.error('计划人员是停用状态');
        query.attributeMaintenanceCommercialPersonnelJobNumer = data1.data.records[0].jobNumber
        query.attributeMaintenanceProjectPersonnelJobNumer = data2.data.records[0].jobNumber
        console.log(query.attributeMaintenanceCommercialPersonnelJobNumer);
        console.log(query.attributeMaintenanceProjectPersonnelJobNumer);
        // query.attributeMaintenanceProjectPersonnelJobNumer
        let res = ''
        if(this.title === '新增'){
          res = await baselineSave(query)
        } else if(this.title === '修改'){
          // query.attributeMaintenanceCreateTime = '' 
          res = await baselineUpd(query)
        }
        // console.log(res);
        if(res.code == '1'){
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogFormVisible = false
          this.handleFilter()
        } else {
          this.$message({
            message: `${res.msg}`,
            type: 'warning'
          })
        }
      },
      // 点击修改按钮，将table表的内容传入弹框内部的表单
      // item为一行的表单数据，为一个对象
      handleEdit(item) {
        this.title = '修改'
        this.attributeMaintenanceMail = item.attributeMaintenanceMail.split(',');
        const attributeMaintenanceMailUserName = item.attributeMaintenanceMailUserName.split(',');
        // 遍历数组，并将每个元素转换为对象
        this.MailUserName = attributeMaintenanceMailUserName.map(name => ({ name }));
        this.modifyform = Object.assign({},item)
        console.log(this.attributeMaintenanceMail);
        console.log(this.MailUserName);
        this.dialogFormVisible = true
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.handleFilter()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.handleFilter()
      },
      // 导出excel
      async hExportExcel() {
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
          console.log(query)
          // if(this.userInfo.departmentName == '喷涂车间') { query.isSpray = true }
          let arr = await orderForecasting(query)
          console.log(arr);
          const desiredProperties = ['attributeMaintenanceCustomerName', 'attributeMaintenanceProductType',
        'attributeMaintenanceCommercialPersonnelUserName','attributeMaintenanceProjectPersonnelUserName',
        'attributeMaintenanceNumericalControlProportion','attributeMaintenanceWeldProportion','attributeMaintenanceSprayProportion',
        'attributeMaintenanceAssembleProportion','attributeMaintenanceMailUserName','attributeMaintenanceUpdateUserName',
        'attributeMaintenanceUpdateTime'];
          const list = arr.data.list.map(function(obj) {
            var filteredObj = {};
            desiredProperties.forEach(function(prop) {
                filteredObj[prop] = obj[prop];
            });
            return filteredObj;
          });
          const {header,data} = this.transformDat(list)
            import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename:'订单属性excel', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
        },
        transformDat(res) {
          const mapInfo = {
            attributeMaintenanceCustomerName: '客户名称',
            attributeMaintenanceProductType: '产品类型',
            attributeMaintenanceCommercialPersonnelUserName: '商务人员',
            attributeMaintenanceProjectPersonnelUserName: '计划人员',
            attributeMaintenanceNumericalControlProportion: '数控占比',
            attributeMaintenanceWeldProportion: '焊接占比',
            attributeMaintenanceSprayProportion: '喷涂占比',
            attributeMaintenanceAssembleProportion: '装配产能',
            attributeMaintenanceMailUserName: '邮件接收人',
            attributeMaintenanceUpdateUserName: '修改人员',
            attributeMaintenanceUpdateTime: '修改时间'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
      getData() {
        this.listQuery.page = 1
        this.listQuery.limit = 10
        this.handleFilter()
      },
    },
    // 在生命周期函数调用"搜索"按钮绑定的函数，显示已有的数据
    async mounted() {
        this.handleFilter()
    },
}
</script>

<style>

</style>